package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

// QuickReplyRepository 快捷回复数据访问层
type QuickReplyRepository struct {
	db *gorm.DB
}

// NewQuickReplyRepository 创建快捷回复仓库
func NewQuickReplyRepository(db *gorm.DB) *QuickReplyRepository {
	return &QuickReplyRepository{db: db}
}

// Create 创建快捷回复
func (r *QuickReplyRepository) Create(reply *model.ChatQuickReply) error {
	return r.db.Create(reply).Error
}

// GetByID 根据ID获取快捷回复
func (r *QuickReplyRepository) GetByID(id uint) (*model.ChatQuickReply, error) {
	var reply model.ChatQuickReply
	err := r.db.First(&reply, id).Error
	if err != nil {
		return nil, err
	}
	return &reply, nil
}

// GetList 获取快捷回复列表
func (r *QuickReplyRepository) GetList(staffID uint, category string, isGlobal *bool, page, pageSize int) ([]model.ChatQuickReply, int64, error) {
	var replies []model.ChatQuickReply
	var total int64

	query := r.db.Model(&model.ChatQuickReply{})

	// 筛选条件：个人话术 + 全局话术
	if isGlobal != nil && *isGlobal {
		// 只看全局话术
		query = query.Where("staff_id = ?", 0)
	} else {
		// 看自己的话术 + 全局话术
		query = query.Where("staff_id IN (?)", []uint{0, staffID})
	}

	// 分类筛选
	if category != "" {
		query = query.Where("category = ?", category)
	}

	// 计数
	query.Count(&total)

	// 分页
	offset := (page - 1) * pageSize
	err := query.Order("sort_order DESC, created_at DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&replies).Error

	return replies, total, err
}

// Update 更新快捷回复
func (r *QuickReplyRepository) Update(id uint, updates map[string]interface{}) error {
	return r.db.Model(&model.ChatQuickReply{}).
		Where("id = ?", id).
		Updates(updates).Error
}

// Delete 删除快捷回复
func (r *QuickReplyRepository) Delete(id uint) error {
	return r.db.Delete(&model.ChatQuickReply{}, id).Error
}

// CheckOwnership 检查所有权
func (r *QuickReplyRepository) CheckOwnership(id, staffID uint) (bool, error) {
	var reply model.ChatQuickReply
	err := r.db.Select("staff_id").First(&reply, id).Error
	if err != nil {
		return false, err
	}
	// 全局话术（staff_id=0）任何人都可以使用，但只有管理员可以修改/删除
	// 个人话术只能本人修改/删除
	return reply.StaffID == staffID || reply.StaffID == 0, nil
}

